<template>
  <div class="apply-manage">
    <div class="page-header">
      <h2>租房申请管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-box">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="待处理" :value="0"></el-option>
            <el-option label="已同意" :value="1"></el-option>
            <el-option label="已拒绝" :value="2"></el-option>
            <el-option label="已取消" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table :data="tableData" border stripe v-loading="loading">
      <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
      <el-table-column prop="houseTitle" label="房源标题" min-width="200"></el-table-column>
      <el-table-column prop="houseAddress" label="房源地址" min-width="200"></el-table-column>
      <el-table-column prop="rentStartTime" label="租期开始" width="100"></el-table-column>
      <el-table-column prop="rentEndTime" label="租期结束" width="100"></el-table-column>
      <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">待处理</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">已同意</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger">已拒绝</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="info">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template slot-scope="scope">
          <!-- 房东端操作 -->
          <template v-if="isLandlord">
            <el-button 
              v-if="scope.row.status === 0" 
              size="mini" 
              type="text" 
              @click="handleAgree(scope.row)">
              同意
            </el-button>
            <el-button 
              v-if="scope.row.status === 0" 
              size="mini" 
              type="text" 
              @click="handleReject(scope.row)" 
              style="color: #f56c6c;">
              拒绝
            </el-button>
          </template>
          <!-- 租客端操作 -->
          <template v-else>
            <el-button 
              v-if="scope.row.status === 0" 
              size="mini" 
              type="text" 
              @click="handleCancel(scope.row)" 
              style="color: #f56c6c;">
              取消申请
            </el-button>
          </template>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-box">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 处理对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
      <el-form :model="handleForm" label-width="100px">
        <el-form-item label="处理备注">
          <el-input 
            type="textarea" 
            v-model="handleForm.handleRemark" 
            :rows="4" 
            placeholder="请输入处理备注（可选）">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RentHouseApply',
  data() {
    return {
      loading: false,
      searchForm: {
        status: ''
      },
      tableData: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      isLandlord: false,  // 判断当前用户是否是房东
      dialogVisible: false,
      dialogTitle: '',
      handleForm: {
        id: null,
        status: null,
        handleRemark: ''
      }
    }
  },
  created() {
    this.checkUserRole()
    this.loadData()
  },
  methods: {
    checkUserRole() {
      // 从localStorage获取用户信息，判断角色
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        try {
          const user = JSON.parse(userInfo)
          // role: 0-租客，1-房东，2-管理员
          this.isLandlord = user.role === 1 || user.role === 2
        } catch (e) {
          console.error('解析用户信息失败:', e)
        }
      }
    },
    loadData() {
      this.loading = true
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        status: this.searchForm.status !== '' ? this.searchForm.status : undefined
      }
      
      // 根据用户角色调用不同的API
      const apiMethod = this.isLandlord ? 
        this.$network.getLandlordApplies : 
        this.$network.getMyApplies
      
      apiMethod(params).then(res => {
        if (res.data.code === 200) {
          this.tableData = res.data.data.list || []
          this.total = res.data.data.total || 0
        } else {
          this.$message.error(res.data.message || '获取申请列表失败')
        }
      }).catch(error => {
        console.error('获取申请列表失败:', error)
        this.$message.error('获取申请列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    handleSearch() {
      this.pageNo = 1
      this.loadData()
    },
    handleReset() {
      this.searchForm = {
        status: ''
      }
      this.pageNo = 1
      this.loadData()
    },
    handleAgree(row) {
      this.dialogTitle = '同意申请'
      this.dialogVisible = true
      this.handleForm = {
        id: row.id,
        status: 1,
        handleRemark: ''
      }
    },
    handleReject(row) {
      this.dialogTitle = '拒绝申请'
      this.dialogVisible = true
      this.handleForm = {
        id: row.id,
        status: 2,
        handleRemark: ''
      }
    },
    handleCancel(row) {
      this.$confirm('确定要取消该申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          id: row.id
        }
        this.$network.cancelApply(data).then(res => {
          if (res.data.code === 200) {
            this.$message.success('取消成功')
            this.loadData()
          } else {
            this.$message.error(res.data.message || '取消失败')
          }
        }).catch(error => {
          console.error('取消申请失败:', error)
          this.$message.error('取消失败')
        })
      }).catch(() => {
        // 取消操作
      })
    },
    handleView(row) {
      // 查看详情
      this.$network.getApplyDetail(row.id).then(res => {
        if (res.data.code === 200) {
          this.$message.success('获取详情成功')
          console.log('申请详情:', res.data.data)
          // TODO: 可以增加详情对话框
        } else {
          this.$message.error(res.data.message || '获取详情失败')
        }
      }).catch(error => {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
      })
    },
    handleSubmit() {
      const data = {
        id: this.handleForm.id,
        status: this.handleForm.status,
        handleRemark: this.handleForm.handleRemark || undefined
      }
      
      this.$network.handleApply(data).then(res => {
        if (res.data.code === 200) {
          this.$message.success('处理成功')
          this.dialogVisible = false
          this.loadData()
        } else {
          this.$message.error(res.data.message || '处理失败')
        }
      }).catch(error => {
        console.error('处理申请失败:', error)
        this.$message.error('处理失败')
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.loadData()
    }
  }
}
</script>

<style scoped>
.apply-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-box {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.pagination-box {
  margin-top: 20px;
  text-align: right;
}
</style>
